package com.xtayfjpk.security.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.Enumeration;

public class SecurityUtils {
	
	public static String toHexString(byte[] data) {// 二行制转字符串
		StringBuilder builder = new StringBuilder();
		String stmp = "";
		for (int n = 0; n < data.length; n++) {
			stmp = (java.lang.Integer.toHexString(data[n] & 0XFF));
			if (stmp.length() == 1) {
				builder.append("0");
			}
			builder.append(stmp);
		}
		return builder.toString().toUpperCase();
	}
	
	public static byte [] readFileContent(File file) {
		byte [] buffer = new byte[(int) file.length()];
		BufferedInputStream is = null;
		try {
			is = new BufferedInputStream(new FileInputStream(file));
			is.read(buffer,  0,  buffer.length);
		} catch (Throwable t) {
			System.err.println("Failed to read byte content of " + file.getAbsolutePath());
			t.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException ioe) {
					System.err.println("Failed to close file " + file.getAbsolutePath());
					ioe.printStackTrace();
				}
			}
		}
		return buffer;
	}
	
	public static KeyStore jks2PKCS12(KeyStore jksKeyStore) throws Exception {
		
		KeyStore pkcsKeyStore = KeyStore.getInstance("pkcs12");
		pkcsKeyStore.load(new FileInputStream("D:\\java-app\\apache-tomcat-6.0.35\\conf\\clientKeyStore.p12"), "gitblit".toCharArray());
		Enumeration<String> aliasEnumeration = jksKeyStore.aliases();
		String keyPassword = "gitblit";
		while(aliasEnumeration.hasMoreElements()) {
			String alias = aliasEnumeration.nextElement();
			pkcsKeyStore.setKeyEntry(alias, jksKeyStore.getKey(alias, 
					keyPassword.toCharArray()), keyPassword.toCharArray(), new Certificate[]{jksKeyStore.getCertificate(alias)});
		}
		
		return pkcsKeyStore;
	}
	
	public static void main(String[] args) throws Exception {
		String keyStorePath = "D:\\java-app\\apache-tomcat-6.0.35\\conf\\serverKeyStore.jks";
		KeyStore keyStore = getKeyStore(keyStorePath, "jks", "gitblit");
		KeyStore pkcsKeyStore = jks2PKCS12(keyStore);
		pkcsKeyStore.deleteEntry("gitblit certificate authority");
		pkcsKeyStore.store(new FileOutputStream("H:/clientKeyStore.p12"), "gitblit".toCharArray());
	}
	
	public static KeyStore getKeyStore(String keyStorePath, String type, String keyStorePassword) throws Exception {
		KeyStore keyStore = KeyStore.getInstance(type);
		FileInputStream in = new FileInputStream(keyStorePath);
		keyStore.load(in, keyStorePassword.toCharArray());
		in.close();
		return keyStore;
	}
}
